package com.shuoyue.ycgk.ui.shop;

import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.entity.ShopCarBean;
import com.shuoyue.ycgk.ui.shop.contract.ShopCarContract;
import com.shuoyue.ycgk.utils.NumberUtils;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.utils.SpacesItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ShoppingCarActivity extends BaseMvpActivity<ShopCarContract.Presenter> implements ShopCarContract.View {

    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshlayout;
    @BindView(R.id.tv_select_all)
    CheckBox tvSelectAll;
    @BindView(R.id.tv_totalPrice)
    TextView tvTotalPrice;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.price_lay)
    LinearLayout priceLay;

    ShoppingCartAdapter adapter;
    List<ShopCarBean> mDatas = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.activity_shoppingcar;
    }


    @Override
    protected void initView() {
        pageTitle.setText("购物车");
        tvRight.setText("管理");
        tvRight.setVisibility(View.VISIBLE);
//        refreshlayout.setEnableLoadMore(false);
        adapter = new ShoppingCartAdapter(mDatas);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 8)));
        recyclerView.setAdapter(adapter);
        refreshlayout.setOnRefreshListener(refreshLayout1 -> {
            mPresenter.getData();
        });
        adapter.setOnItemChildClickListener((adapter1, view, position) -> {
            ShopCarBean item = adapter.getItem(position);
            switch (view.getId()) {
                case R.id.lay_all:
                    startActivity(new Intent(mContext, ShopInfoActivity.class)
                            .putExtra("id", item.getProductId()));
                    break;
                case R.id.tv_add:
                    item.setNum(item.getNum() + 1);
                    adapter.notifyDataSetChanged();
                    if (mCompositeDisposable != null) {
                        mCompositeDisposable.clear(); // clear时网络请求会随即cancel
                        mCompositeDisposable = null;
                    }
                    mPresenter.updateNum(item.getId(), item.getNum());

                    changeState();
                    break;
                case R.id.tv_reduce:
                    if (item.getNum() > 1) {
                        item.setNum(item.getNum() - 1);
                        adapter.notifyDataSetChanged();
                        if (mCompositeDisposable != null) {
                            mCompositeDisposable.clear(); // clear时网络请求会随即cancel
                            mCompositeDisposable = null;
                        }
                        mPresenter.updateNum(item.getId(), item.getNum());
                        changeState();
                    }

                    break;
                case R.id.tv_check:
                    item.setSelect(((CheckBox) view).isChecked());
                    changeState();
                    adapter.notifyDataSetChanged();
                    break;
            }
        });
        registFinishLoad(refreshlayout);
        registEmptyView(adapter);

    }

    @Override
    public void initData() {
        mPresenter = new ShopCarContract.Presenter();
        mPresenter.attachView(this);
        mPresenter.getData();
    }

    @OnClick({R.id.back, R.id.tv_submit, R.id.tv_select_all, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_submit:
                if (tvRight.getText().equals("管理")) {
                    buy();
                } else if (tvRight.getText().equals("取消")) {
                    delete();
                }
                break;
            case R.id.tv_select_all:
                tvSelectAll.setChecked(tvSelectAll.isChecked());
                for (ShopCarBean shopCarBean : mDatas) {
                    shopCarBean.setSelect(tvSelectAll.isChecked());
                }
                adapter.notifyDataSetChanged();
                changeState();
                break;
            case R.id.tv_right:
                if (tvRight.getText().equals("管理")) {
                    tvRight.setText("取消");
                    priceLay.setVisibility(View.INVISIBLE);
                } else if (tvRight.getText().equals("取消")) {
                    priceLay.setVisibility(View.VISIBLE);
                    tvRight.setText("管理");
                }
                changeButtonState();
                break;
        }
    }


    @Override
    public void setData(List<ShopCarBean> list) {
        mDatas.clear();
        mDatas.addAll(list);
        adapter.notifyDataSetChanged();
        changeState();
        pageTitle.setText("购物车(" + list.size() + ")");
        refreshlayout.finishRefresh();
        refreshlayout.finishLoadMore();
    }

    @Override
    public void deleteSuc() {
        mPresenter.getData();
    }

    @Override
    public void updateSuc() {

    }


    void delete() {
        StringBuilder stringBuilder = new StringBuilder();
        for (ShopCarBean shopCarBean : adapter.getSelect()) {
            if (stringBuilder.length() != 0) {
                stringBuilder.append(",");
            }
            stringBuilder.append(shopCarBean.getId());
        }
        if (stringBuilder.length() == 0) {
            toast("请选择商品");
            return;
        }
        mPresenter.delete(stringBuilder.toString());
    }

    void buy() {
        ArrayList<String> ids = new ArrayList<>();
        HashMap<Integer, Integer> numParams = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();

        for (ShopCarBean shopCarBean : adapter.getSelect()) {
            ids.add(shopCarBean.getProductId() + "");
            if (numParams.get(shopCarBean.getProductId()) == null) {
                numParams.put(shopCarBean.getProductId(), shopCarBean.getNum());
            } else {
                numParams.put(shopCarBean.getProductId(), numParams.get(shopCarBean.getProductId()) + shopCarBean.getNum());
            }
            if (stringBuilder.length() != 0) {
                stringBuilder.append(",");
            }
            stringBuilder.append(shopCarBean.getId());
        }
        if (ids.size() == 0) {
            toast("请选择商品");
            return;
        }
//        startActivity(new Intent(mContext, ConfirOrderShopActivity.class)
//                .putExtra("ids", ids)
//                .putExtra("num", numParams)
//                .putExtra("shoppingcarIds", stringBuilder.toString()));
        // TODO
    }

    void changeButtonState() {
        if (tvRight.getText().equals("管理")) {
            tvSubmit.setText("结算(" + adapter.getSelect().size() + ")");
        } else if (tvRight.getText().equals("取消")) {
//            tvSubmit.setText("删除");
            tvSubmit.setText("删除(" + adapter.getSelect().size() + ")");
        }
    }

    void changeCheckState() {
        List<ShopCarBean> selectBeans = adapter.getSelect();
        if (selectBeans.size() == mDatas.size() && selectBeans.size() != 0) {
            tvSelectAll.setChecked(true);
        } else {
            tvSelectAll.setChecked(false);
        }
        float priceSum = 0f;
        //TODO  重写下，转String了，需要强转计算
//        for (ShopCarBean shopCarBean : selectBeans) {
//            priceSum += shopCarBean.getProduct().getDefaultPrice() == null
//                    ? 0 : shopCarBean.getProduct().getDefaultPrice().getPrice() * shopCarBean.getNum();
//        }
        tvTotalPrice.setText("￥" + NumberUtils.getFloat(priceSum));
    }

    public void changeState() {
        changeButtonState();
        changeCheckState();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
